package com.aqielife.demo.service.impl;

import com.aqielife.demo.entity.City;
import com.aqielife.demo.service.CityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.core.ReactiveValueOperations;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author aqie
 * @date 2022/02/04 22:14
 * @desc
 */
@Slf4j
@Service("cityServiceRedisImpl")
public class CityServiceRedisImpl implements CityService {

  @Autowired
  private ReactiveRedisTemplate<String, City> reactiveRedisTemplate;;

  @Override
  public Mono<City> save(City city) {
    return null;
  }

  @Override
  public Mono<City> findCityById(String id) {
    String key = "city_" + id;
    ReactiveValueOperations<String, City> operations = reactiveRedisTemplate.opsForValue();
    Mono<City> monoCity = operations.get(key);
    return monoCity;
  }

  @Override
  public Flux<City> findAllCity() {
    return null;
  }

  @Override
  public Mono<City> modifyCity(City city) {
    // 修改redis 缓存
    String key = "city_" + city.getId();
    ReactiveValueOperations<String, City> operations = reactiveRedisTemplate.opsForValue();
    Mono<City> cityMono = operations.getAndSet(key, city);
    return cityMono;
  }

  @Override
  public void deleteCity(String id) {
    // 删除redis 缓存
    String key = "city_" + id;
    log.info("delete {}", key);
    reactiveRedisTemplate.delete(key)
    .subscribe(count -> log.info("Removed {}", count));;
  }
}
